/*
 * Copyright (C) 2018 The Asiainfo-Ability Authors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package org.asiainfo.ability.gateway.filter;

import com.netflix.client.http.HttpHeaders;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.asiainfo.ability.base.code.CallState;
import org.asiainfo.ability.base.service.TraceService;
import org.asiainfo.ability.base.utils.ExceptionUtils;
import org.asiainfo.ability.base.utils.StringUtils;
import org.asiainfo.ability.base.vo.CallerTrace;
import org.asiainfo.ability.base.vo.Record;
import org.asiainfo.ability.gateway.context.AbilityRequestContext;
import org.asiainfo.ability.gateway.service.support.AbilityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpResponse;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * @Author: visen
 * @Date: 2018/1/16
 * @Description:
 */
public class FinalFilter extends ZuulFilter {
    private static final Logger logger = LogManager.getLogger(FinalFilter.class);


    private AbilityService abilityService;
    @Autowired
    private TraceService traceService;

    public void setAbilityService(AbilityService abilityService) {
        this.abilityService = abilityService;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String error = (String) ctx.get("error");
        if (!StringUtils.isBlank(error)) {
            try {
                ctx.setResponseBody(new String(error.getBytes("GBK"), "ISO-8859-1"));
                ctx.getResponse().setStatus(HttpStatus.BAD_REQUEST.value());
            } catch (UnsupportedEncodingException e) {
                ExceptionUtils.logTrace(logger, e);
            }
        }
        AbilityRequestContext requestContext = (AbilityRequestContext)ctx.get(AbilityRequestContext.CONTEXT_KEY);

        if(requestContext != null) {
            CallerTrace callerTrace = requestContext.getCallerTrace();
            callerTrace.setEndTime(System.currentTimeMillis());
            callerTrace.setCostTime(Long.valueOf(callerTrace.getEndTime() - callerTrace.getBeginTime()).intValue());

            if(ctx.getResponse().getStatus() != HttpStatus.BAD_REQUEST.value()) {
                callerTrace.setState(CallState.SUCCESS);
                HttpHeaders httpHeaders = ((RibbonApacheHttpResponse)ctx.get("ribbonResponse"))
                        .getHttpHeaders();
                String reqTime = httpHeaders.getFirstValue("X-Req-Time");
                String respTime = httpHeaders.getFirstValue("X-Resp-Time");
                if(!StringUtils.isBlank(respTime)) {
                    try {
                        callerTrace.setCostNetTime((int)((Long.parseLong(reqTime) - callerTrace.getBeginTime() +
                                callerTrace.getEndTime() - Long.parseLong(respTime))/2));
                    }catch(Exception e) {
                        ExceptionUtils.logTrace(logger, e);
                    }

                }
            } else {
                String summary = (String)ctx.get("errorSummary");
                if(StringUtils.isBlank(summary)) {
                    summary = ctx.getResponseBody();
                }
                callerTrace.setSummary(summary);
                callerTrace.setState(CallState.FAILURE);
            }
            traceService.saveCallerTrace(callerTrace);
        }

        return null;

    }
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public int filterOrder() {
        return 999;
    }

    @Override
    public String filterType() {
        return "post";
    }
}